package mailUtil

import (
	"crypto/tls"
	"errors"
	"fmt"
	util2 "go-api-template/internal/util"
	"go-api-template/service"
	"time"

	"gopkg.in/gomail.v2"
)

var (
	log   = service.Log
	redis = service.Redis // 使用前配置设置: redis.enable: true
)

type VerificationCode struct {
	mail  string
	event string
}

//SendMail 发送邮件
func SendMail(mailTo []string, subject string, body string) error {
	fmt.Printf("%+v", service.Conf.Mail)
	// 设置Message
	m := gomail.NewMessage()
	m.SetHeader("From", service.Conf.Mail.User) //这种方式可以添加别名，即“XD Game”， 也可以直接用<code>m.SetHeader("From",mailConn["front"])</code> 读者可以自行实验下效果
	m.SetHeader("To", mailTo...)                //发送给多个用户
	m.SetHeader("Subject", subject)             //设置邮件主题
	m.SetBody("text/html", body)                //设置邮件正文

	// 设置smtp拨号器
	d := gomail.Dialer{
		Host:     service.Conf.Mail.Host,
		Port:     service.Conf.Mail.Port,
		Username: service.Conf.Mail.User,
		Password: service.Conf.Mail.Password,
		SSL:      service.Conf.Mail.SSL,
	}

	// 使用tls
	d.TLSConfig = &tls.Config{
		InsecureSkipVerify: false,
		ServerName:         service.Conf.Mail.Host,
	}

	// 发送邮件
	err := d.DialAndSend(m)
	if err != nil {
		fmt.Println(err.Error())
	}

	return err

}

//SendCode 发送验证码
func SendCode(mail string, event string) (err error) {
	code := util2.GetCode(6)

	if redis == nil {
		err = errors.New("未连接Redis")
		return
	}

	if mail == "" {
		err = errors.New("邮箱参数为空")
		return
	}

	redisKey := fmt.Sprintf("mail.%s.%s", event, mail)
	log.Debug(redisKey)
	body := fmt.Sprintf("亲爱的用户! 您的验证码是: %s", code)
	if SendMail([]string{mail}, "短信验证码", body) != nil {
		err = errors.New("验证码发送失败")
		return
	}

	err = redis.Set(redisKey, code, 3*time.Minute).Err()
	return
}
